<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item>
                <i class="el-icon-view"></i>
                脏器设置
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row>
                <el-tabs
                    v-model="typeActiveTab"
                    @tab-click="typeActiveTabClick"
                    type="card"
                >
                    <el-tab-pane
                        label="脏器信息"
                        name="organ"
                    >
                        <el-row>
                            <el-button
                                @click="organDialogOpen(-1)"
                                type="primary"
                                size="mini"
                                style="float: right"
                            >新增脏器
                            </el-button>
                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane
                        label="指标信息"
                        name="indicator"
                    >
                        <el-row>
                            <el-button
                                @click="indicatorDialogOpen(-1)"
                                type="primary"
                                size="mini"
                                style="float: right"
                            >新增指标
                            </el-button>
                        </el-row>
                    </el-tab-pane>
                </el-tabs>
            </el-row>
            <el-row style="margin-top: 10px;">
                <base-table
                    ref="table"
                    :data="table.data"
                    :header="table.header"
                    :operation="table.operation"
                    :pageInfo="table.pageInfo"
                    :selected="false"
                    @handleClick="tableButtonClick"
                    @pageJumpTo="tablePageJumpTo"
                    @sizeChange="tableSizeChange"
                >
                </base-table>
            </el-row>
        </div>
        <el-dialog
            :visible.sync="organDialog.visible"
            :title="organDialog.title"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="40%"
        >
            <el-form
                ref="organDialogForm"
                label-width="80px"
                :model="organDialogForm"
                :rules="organDialogFormRules"
            >
                <el-row class="line-text row-padding-bottom">
                    <el-col :span="11">
                        <el-form-item
                            label="名称"
                            prop="name"
                        >
                            <el-input
                                v-model="organDialogForm.name"
                                placeholder="请输入脏器名称"
                                class="input-form"
                                size="mini"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col
                        :span="11"
                        :offset="1"
                    >
                        <el-form-item label="备注">
                            <el-input
                                v-model="organDialogForm.remark"
                                placeholder="请输入备注"
                                class="input-form"
                                size="mini"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="line-text row-padding-bottom">
                    <el-col :span="11">
                        <el-form-item
                            label="人体系统"
                            prop="humanBodySystem"
                        >
                            <el-select
                                v-model="organDialogForm.humanBodySystem"
                                placeholder="请选择人体系统"
                                clearable
                                class="picker-form"
                                size="mini"
                            >
                                <el-option
                                    v-for="item in humanBodySystemList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col
                        :span="11"
                        :offset="1"
                    >
                        <el-form-item label="序号">
                            <el-input
                                v-model="organDialogForm.organSortNo"
                                placeholder="请输入序号"
                                class="input-form"
                                size="mini"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <el-row
                class="line-text"
                style="margin-top: 10px"
            >
                <el-col :span="11">
                    <el-input
                        v-model="organDialog.bodyInput"
                        placeholder="请输入部位名称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                    <el-button
                        @click="bodyInputAdd"
                        style="float: right"
                        type="primary"
                        size="mini"
                    >添加部位
                    </el-button>
                </el-col>
                <el-col
                    :span="11"
                    :offset="1"
                >
                    <el-select
                        v-model="organDialog.indicatorSelected"
                        placeholder="请选择指标"
                        multiple
                        filterable
                        remote
                        size="mini"
                        class="picker-form"
                    >
                        <el-option
                            v-for="(data, index) in organDialog.indicatorsAll"
                            :key="data.id"
                            :label="data.name"
                            :value="index"
                        >
                        </el-option>
                    </el-select>
                    <el-button
                        @click="indicatorSelectedAdd"
                        style="float: right"
                        type="primary"
                        size="mini"
                    >添加指标
                    </el-button>
                </el-col>
            </el-row>
            <el-row
                class="line-text"
                style="margin-top: 10px"
            >
                <el-col :span="11">
                    <base-table
                        ref="bodyTable"
                        class="data-table-style"
                        :data="bodyTable.data"
                        :header="bodyTable.header"
                        :operation="bodyTable.operation"
                        :pageInfo="bodyTable.pageInfo"
                        :pageSizes="[10, 15, 20]"
                        :selected="false"
                        @handleClick="bodyTableButtonClick"
                    >
                    </base-table>
                </el-col>
                <el-col
                    :span="11"
                    :offset="1"
                >
                    <base-table
                        ref="indicatorTable"
                        class="data-table-style"
                        :data="indicatorTable.data"
                        :header="indicatorTable.header"
                        :operation="indicatorTable.operation"
                        :pageInfo="indicatorTable.pageInfo"
                        :pageSizes="[10, 15, 20]"
                        :selected="false"
                        @handleClick="indicatorTableButtonClick"
                    >
                    </base-table>
                </el-col>
            </el-row>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="organDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="organDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="indicatorDialog.visible"
            :title="indicatorDialog.title"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="25%"
        >
            <el-form
                ref="indicatorDialogForm"
                label-width="150px"
                :model="indicatorDialogForm"
                :rules="indicatorDialogFormRules"
            >
                <el-form-item
                    class="row-padding-bottom"
                    label="指标名称"
                    prop="name"
                >
                    <el-input
                        v-model="indicatorDialogForm.name"
                        placeholder="请输入指标名称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="指标简称"
                    class="row-padding-bottom"
                >
                    <el-input
                        v-model="indicatorDialogForm.abbreviation"
                        placeholder="请输入指标简称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="单位"
                    class="row-padding-bottom"
                >
                    <el-input
                        v-model="indicatorDialogForm.unit"
                        placeholder="请输入单位"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="参考值"
                    class="row-padding-bottom"
                >
                    <el-input
                        v-model="indicatorDialogForm.referValue"
                        placeholder="请输入参考值"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        v-model="indicatorDialogForm.remark"
                        placeholder="请输入备注"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="indicatorDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="indicatorDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';
import { itemsPerPage } from '../../libs/util';
import { vxRule } from '@/client/libs/validator';

const organTableProperty = {
    header: [
        {
            label: '脏器名称',
            prop: 'name',
            width: '160',
        },
        {
            label: '人体系统',
            prop: 'humanBodySystemName',
            width: '160',
        },
        {
            label: '关联部位',
            prop: 'body',
            width: '380',
        },
        {
            label: '关联指标',
            prop: 'indicatorString',
        },
        {
            label: '备注',
            prop: 'remark',
            width: '180',
        },
    ],
    operation: [
        {
            label: '编辑',
            functionKey: 'tableOrganEdit',
        },
        {
            label: '删除',
            color: 'red',
            functionKey: 'tableDelete',
        },
    ],
};
const indicatorTableProperty = {
    header: [
        {
            label: '指标名称',
            prop: 'name',
            width: '200',
        },
        {
            label: '指标简称',
            prop: 'abbreviation',
            width: '200',
        },
        {
            label: '单位',
            prop: 'unit',
        },
        {
            label: '参考值',
            prop: 'referValue',
        },
        {
            label: '套餐说明',
            prop: 'remark',
        },
    ],
    operation: [
        {
            label: '编辑',
            functionKey: 'tableIndicatorEdit',
        },
        {
            label: '删除',
            color: 'red',
            functionKey: 'tableDelete',
        },
    ],
};
export default {
    name: 'InstitutionOrgans',
    components: {
        BaseTable,
    },
    data() {
        return {
            typeActiveTab: 'organ',

            table: {
                data: [],
                header: [],
                operation: [],
                pageInfo: {
                    page: 1,
                    size: 15,
                    total: 0,
                },
            },
            organDialog: {
                visible: false,
                title: '',
                commitMethod: '',

                bodyInput: '',
                indicatorSelected: [],
                indicatorsAll: [],
            },
            organDialogForm: {
                id: 0,
                name: '',
                body: '',
                humanBodySystem: '',
                organSortNo: '',
                remark: '',
                bodyList: [],
                indicatorList: [],
                institutionId: this.$store.state.institution.id,
            },
            humanBodySystemList: [],
            dictRequestMap: [
                {
                    code: 'humanBodySystem',
                    arrayKey: 'humanBodySystemList',
                },
            ],

            organDialogFormRules: {
                name: [
                    vxRule(true, null, 'blur', '请填写名称'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '名称填写请不要超过50个字符',
                        null,
                        50
                    ),
                ],
                humanBodySystem: [vxRule(true, null, 'blur', '请选择人体系统')],
            },

            bodyTable: {
                data: [],
                header: [
                    {
                        label: '部位名称',
                        prop: 'name',
                    },
                ],
                operation: [
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'bodyTableDelete',
                    },
                ],
                pageInfo: {
                    hide: true,
                    page: 1,
                    size: 0,
                    total: 0,
                },
            },

            indicatorTable: {
                data: [],
                header: [
                    {
                        label: '指标名称',
                        prop: 'name',
                    },
                ],
                operation: [
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'indicatorTableDelete',
                    },
                ],
                pageInfo: {
                    hide: true,
                    page: 1,
                    size: 0,
                    total: 0,
                },
            },

            indicatorDialog: {
                visible: false,
                title: '',
                commitMethod: '',
            },
            indicatorDialogForm: {
                id: 0,
                name: '',
                abbreviation: '',
                unit: '',
                referValue: '',
                remark: '',
                institutionId: this.$store.state.institution.id,
            },
            indicatorDialogFormRules: {
                name: [
                    vxRule(true, null, 'blur', '请填写指标名称'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '指标名称填写请不要超过50个字符',
                        null,
                        50
                    ),
                ],
            },
        };
    },
    mounted() {
        this.tableInit();
        this.dictionariesRequest();
    },
    computed: {
        requestInterface() {
            if (this.typeActiveTab === 'organ') {
                return '/organs';
            }
            if (this.typeActiveTab === 'indicator') {
                return '/indicator';
            }
            return '';
        },
    },
    methods: {
        // 字典数据请求
        async dictionariesRequest() {
            this.dictRequestMap.forEach((map) => {
                this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: {
                        code: map.code,
                        page: 0,
                        size: 99,
                    },
                }).then(async (res) => {
                    if ((await res) && (await res.data.code) === 200) {
                        this[map.arrayKey] = _.clone(res.data.data);
                    }
                });
            });
        },
        tableInit() {
            const baseTable = {
                data: [],
                header: [],
                operation: [],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            };

            if (this.typeActiveTab === 'organ') {
                baseTable.header = _.clone(organTableProperty.header);
                baseTable.operation = _.clone(organTableProperty.operation);
                this.table = baseTable;
                this.tableDataRequest();
            } else if (this.typeActiveTab === 'indicator') {
                baseTable.header = _.clone(indicatorTableProperty.header);
                baseTable.operation = _.clone(indicatorTableProperty.operation);
                this.table = baseTable;
                this.indicatorTableDataRequest();
            }
        },
        typeActiveTabClick() {
            this.tableInit();
        },
        async tableDataRequest() {
            try {
                const { state } = this.$store;
                await this.$axios({
                    method: 'GET',
                    url: `/PROXY-Remote${this.requestInterface}`,
                    params: {
                        institutionId: state.institution.id,
                        size: this.table.pageInfo.size,
                        page: this.table.pageInfo.page - 1,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    this.table.pageInfo = {
                        total: result.pageInfo.total,
                        page: result.pageInfo.page + 1,
                        size: result.pageInfo.size,
                    };
                    this.table.data = [];
                    result.data.forEach((t, index) => {
                        const item = t;
                        item.index = index;

                        if (this.typeActiveTab === 'organ') {
                            // 部位数据处理
                            item.bodyList = [];
                            if (t.body) {
                                const tempBodyList = t.body.split(' ');
                                tempBodyList.forEach((body) => {
                                    if (!!body) {
                                        item.bodyList.push({
                                            name: body,
                                        });
                                    }
                                });
                            }

                            // 指标数据处理
                            item.indicatorString = '';
                            item.indicatorList.forEach((indicator) => {
                                item.indicatorString += `${indicator.name} `;
                            });
                        }

                        this.table.data.push(item);
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        async indicatorTableDataRequest() {
            try {
                await this.$axios({
                    method: 'POST',
                    url: `/PROXY-Remote/indicator/findAll`,
                    data: {
                        size: this.table.pageInfo.size,
                        page: this.table.pageInfo.page - 1,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    this.table.pageInfo = {
                        total: result.pageInfo.total,
                        page: result.pageInfo.page + 1,
                        size: result.pageInfo.size,
                    };
                    this.table.data = [];
                    result.data.forEach((t, index) => {
                        const item = t;
                        item.index = index;
                        this.table.data.push(item);
                    });
                });
            } catch (e) {
                // 跳出
            }
        },

        // 主页面表格操作
        tableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        tablePageJumpTo(val) {
            this.table.pageInfo.page = val;
            // 为 table.data 赋值相应页上新数据
            if (this.typeActiveTab === 'organ') {
                this.tableDataRequest();
            } else {
                this.indicatorTableDataRequest();
            }
        },
        tableSizeChange(val) {
            this.table.pageInfo.size = val;
            this.table.pageInfo.page = 1;
            // 为 table.data 赋值相应数据量新数据
            if (this.typeActiveTab === 'organ') {
                this.tableDataRequest();
            } else {
                this.indicatorTableDataRequest();
            }
        },
        tableDelete(row) {
            const delName = row.hasOwnProperty('humanBodySystemName')
                ? '脏器'
                : '指标';
            this.$confirm(`删除该${delName}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    try {
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: 'DELETE',
                            url: `/PROXY-Remote${this.requestInterface}/${row.id}`,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code !== 200) {
                                throw new Error(res.data);
                            }

                            // 请求成功
                            this.$message.success('删除成功!');
                            if (this.table.data.length === 1) {
                                if (this.table.pageInfo.page > 1) {
                                    this.table.pageInfo.page -= 1;
                                }
                            }
                            this.tableDataRequest();
                        });
                    } catch (e) {
                        // 跳出
                    }
                })
                .catch(() => {});
        },
        tableOrganEdit(row) {
            this.organDialogOpen(row.index);
        },
        tableIndicatorEdit(row) {
            this.indicatorDialogOpen(row.index);
        },
        // 脏器对话框
        organDialogOpen(index) {
            this.organDialogForm = {
                id: 0,
                name: '',
                body: '',
                humanBodySystem: '',
                organSortNo: '',
                remark: '',
                bodyList: [],
                indicatorList: [],
                institutionId: this.$store.state.institution.id,
            };

            this.organDialog.indicatorSelected = [];
            if (index < 0) {
                this.organDialog.title = '新增脏器';
                this.organDialog.commitMethod = 'POST';
                // 新增字典不带 id 字段
                delete this.organDialogForm.id;

                this.bodyTable.data = [];
                this.indicatorTable.data = [];
            } else {
                this.organDialog.title = '编辑脏器';
                this.organDialog.commitMethod = 'PUT';
                // 赋值
                Object.keys(this.organDialogForm).forEach((key) => {
                    this.organDialogForm[key] = this.table.data[index][key];
                });
                this.bodyTable.data = _.clone(this.table.data[index].bodyList);
                this.indicatorTable.data = _.clone(
                    this.table.data[index].indicatorList
                );
            }

            this.organDialog.bodyInput = '';
            this.organDialog.indicatorSelected = [];
            this.indicatorsRequestAll();
            this.organDialog.visible = true;
        },
        // 脏器对话框-添加部位到脏器
        bodyInputAdd() {
            // 以空格划分
            const nameList = this.organDialog.bodyInput.split(' ');
            if (nameList.length !== 0 && this.validateForm()) {
                nameList.forEach((name) => {
                    const isRepeat = this.bodyTable.data.some(
                        (t) => t.name === name
                    );
                    if (isRepeat) {
                        this.$message.warning('部位重复');
                    } else {
                        this.bodyTable.data.push({
                            name,
                        });
                        this.organDialog.bodyInput = '';
                    }
                });
            }
        },
        validateForm() {
            let decide = false;
            this.$refs.organDialogForm.validate((valid) => {
                if (valid) {
                    decide = true;
                } else {
                    this.activeName = 'basicInformation';
                }
            });
            return decide;
        },
        // 脏器对话框-指标表格
        bodyTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        bodyTableDelete(row) {
            this.bodyTable.data.forEach((t, index) => {
                if (t.name === row.name) {
                    this.bodyTable.data.splice(index, 1);
                }
            });
        },
        // 脏器对话框-添加指标到脏器
        indicatorSelectedAdd() {
            if (this.organDialog.indicatorSelected.length === 0) {
                this.$message.warning('请选择指标');
            } else {
                let isAddOne = false;
                this.organDialog.indicatorSelected.forEach((index) => {
                    const indicator = this.organDialog.indicatorsAll[index];
                    const isRepeat = this.indicatorTable.data.some(
                        (t) => t.name === indicator.name
                    );
                    if (!isRepeat) {
                        isAddOne = true;
                        this.indicatorTable.data.push(indicator);
                    }
                });
                if (!isAddOne) {
                    this.$message.warning('指标重复, 请重新添加');
                }
                this.organDialog.indicatorSelected = [];
            }
        },
        // 脏器对话框-指标表格
        indicatorTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        indicatorTableDelete(row) {
            this.indicatorTable.data.forEach((t, index) => {
                if (t.name === row.name) {
                    this.indicatorTable.data.splice(index, 1);
                }
            });
        },
        organDialogCommit() {
            this.$refs.organDialogForm.validate(async (valid) => {
                if (valid) {
                    const filterBodyList = this.organDialogForm.bodyList.filter(
                        (item) => {
                            return !!item.name;
                        }
                    );
                    this.organDialogForm.bodyList = filterBodyList || [];
                    // 部位数据结构格式化
                    this.organDialogForm.body = '';
                    this.bodyTable.data.forEach((t) => {
                        this.organDialogForm.body += `${t.name} `;
                    });
                    // 接口数据结构格式化
                    this.organDialogForm.indicatorList = [];
                    this.indicatorTable.data.forEach((t) => {
                        this.organDialogForm.indicatorList.push({
                            id: t.id,
                        });
                    });
                    try {
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: this.organDialog.commitMethod,
                            url: `/PROXY-Remote${this.requestInterface}`,
                            data: this.organDialogForm,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code === 200) {
                                // 请求成功
                                this.$message.success(
                                    `${this.organDialog.title}成功`
                                );
                                this.organDialog.visible = false;
                                this.tableDataRequest();
                            } else if (res.data.code === 409) {
                                this.$message.warning(res.data.message);
                            }
                        });
                    } catch (e) {
                        // 跳出
                    }
                }
            });
        },

        // 打开指标对话框
        indicatorDialogOpen(index) {
            this.indicatorDialogForm = {
                id: 0,
                name: '',
                abbreviation: '',
                unit: '',
                referValue: '',
                remark: '',
                institutionId: this.$store.state.institution.id,
            };
            if (index < 0) {
                this.indicatorDialog.title = '新增指标';
                this.indicatorDialog.commitMethod = 'POST';
                // 新增字典不带 id 字段
                delete this.indicatorDialogForm.id;
            } else {
                this.indicatorDialog.title = '编辑指标';
                this.indicatorDialog.commitMethod = 'PUT';
                // 赋值
                Object.keys(this.indicatorDialogForm).forEach((key) => {
                    this.indicatorDialogForm[key] = this.table.data[index][key];
                });
            }

            this.indicatorDialog.visible = true;
        },
        // 指标对话框提交
        indicatorDialogCommit() {
            this.$refs.indicatorDialogForm.validate(async (valid) => {
                if (valid) {
                    try {
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: this.indicatorDialog.commitMethod,
                            url: `/PROXY-Remote${this.requestInterface}`,
                            data: this.indicatorDialogForm,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code !== 200) {
                                throw new Error(res.data);
                            }

                            // 请求成功
                            this.$message.success(
                                `${this.indicatorDialog.title}成功`
                            );

                            this.indicatorDialog.visible = false;
                            this.tableDataRequest();
                        });
                    } catch (e) {
                        // 跳出
                    }
                }
            });
        },
        // 请求指标数据
        async indicatorsRequestAll() {
            try {
                const { state } = this.$store;
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/indicator/findAllIdAndName',
                    params: {
                        institutionId: state.institution.id,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    this.organDialog.indicatorsAll = [];
                    result.data.forEach((t) => {
                        this.organDialog.indicatorsAll.push({
                            id: t.id,
                            name: t.name,
                        });
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
    },
};
</script>

<style scoped>
.row-padding-bottom {
    padding-bottom: 10px;
}
.data-table-style >>> .el-table__fixed-body-wrapper {
    top: 40px !important;
}
</style>
